var user = new Object;

$(function(){
    bindingLoginAction(); 
});
function bindingLoginAction(){
    $("#loginBtn").click(loginFromHead);
    $("#logoutBtn").click(logout);
    $("#register").click(showRegister);
    $(".floatbox  input").blur(blurRegistor);
    $(".floatbox  input").focus(focusRegistor);
}
function showRegister(){
    //    floatbox("login");
    $("#div14").css("height", document.body.scrollHeight);
	var left = (document.body.clientWidth - screen.width)/2;
	$("#div14").css("margin-left", left);
	$("#div14").css("width",screen.width);
    $("#div14").show();
    $("#registerForm").show();
    center("registerForm");
}
function showLogin(){
    //    floatbox("login");
    $("#div14").css("height", document.body.scrollHeight);
	var left = (document.body.clientWidth - screen.width)/2;
	$("#div14").css("margin-left", left);
	$("#div14").css("width",screen.width);
    $("#div14").show();
    $("#loginForm").show();
    center("loginForm");
}

function center(divId){
    var thedom = $("#"+divId);
    thedom.css("position","fixed");
    thedom.css("top", (($(window).height() - thedom.outerHeight()) / 2) + $(window).scrollTop() + "px");
    thedom.css("left", (($(window).width() - thedom.outerWidth()) / 2) + $(window).scrollLeft() + "px");
}
function doSearch(){
    var searchString = $("#searchinput").val();
    if($.trim(searchString) != ""){
        location.href = "do?module=category&action=search&search="+searchString;
    }
}

function doSuggest(){
    //cancelable ajax
    var xhr;
    var search = $("#searchinput").val();
    (function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'do?module=category&action=suggest&search='+search,
            dataType:"json",
            success: function(returnData) {
                var suggestSelect = "<select onselect='getSelect(this.value)'>";
                for(var index in returnData){
                    suggestSelect += "<option>" +returnData[index] + "</option>";
                }
                suggestSelect += "</ul>";
                $("#suggestarea").html(suggestSelect);
            }
        });
    })();
}

function getSuggest(){
    
}
function doRegister(){

    var username = $("#regUsername").val();
    var password = $("#regPassword").val();
    var rePassword=$("#regRePassword").val();
    var email = $("#regEmail").val();
    var verifyCode = $("#regCode").val();
    //check the code 
    if(checkForm("#registerForm")){
        $.ajax({
            async:false,
            method:"get",
            url:"do?module=user",
            dataType:"json",
            data:{
                "action":"register",
                "username":username,
                "password":password,
                "email":email,
                "verify":verifyCode
            },
            success:function(returnData){
                if(returnData.status == "success"){
/*                    $(".floatbox").hide();
                    $("#div14").hide();*/
                    login(username, password);
                }
            }
        });
    //end after checkCode
    }
    return false;
}
function checkForm(theFrom){
    if($(theFrom +" input").hasClass("error")){
        infobox("您的注册表单有错误.");
        return false;
    }else{
        return true;
    };
}
function showForm(loginOrRegister){
    $(".floatbox").hide();
    $("#"+loginOrRegister+"Form").show();
    center(loginOrRegister+"Form");
}

function cancelForm(){
    $(".floatbox").hide();
    $("#div14").hide();
}

function blurRegistor(e){
    infobox("");
    var theDom = $(e.srcElement);
    if($.trim(theDom.val()) == ""){
        theDom.val("");
        theDom.addClass("error");
        infobox("加星 (*) 区域必须填写");
    }else{
        if(theDom.attr("type") == "password"){
            if(theDom.val().length < 5){
                theDom.addClass("error");
                infobox("密码长度要大于 5");
            }      
        }
        if(theDom.attr("name") == "regRePassword"){
            if($("input[name=regPassword]").val() != $("input[name=regRePassword]").val()){
                theDom.addClass("error");
                infobox("两次输入的密码不一致,请重新填写");
            }
        }
        if(theDom.attr("name") == "regEmail"){
            var emailReg = /.*@.*\..*/; 
            if(!emailReg.test(theDom.val())){
                theDom.addClass("error");
                infobox("您输入的电子邮件格式错误！");
            }
        }
        if(theDom.attr("name") == "regUsername" && theDom.val() != ""){
            $.ajax({
                url:"do?module=user&action=checkusername&username="+theDom.val(),
                async:false,
                method:"get",
                dataType:"json",
                success:function(result){
                    if(result.status == "success"){
                        theDom.addClass("error");
                        infobox("此用户名已存在，请使用一个新名称！");
                    }
                }            
            });
        }
        if(theDom.attr("name") == "regCode" && theDom.val() != ""){
            $.ajax({
                url:"do?module=verify&action=checkverify&verify="+theDom.val(),
                async:false,
                method:"get",
                dataType:"json",
                success:function(result){
                    if(result.status == "error"){
                        theDom.addClass("error");
                        infobox("您输入的验证码错误！");
                    }
                }
            });
        }
    }
    if(theDom.hasClass("error")){
        return false;
    }else{
        return true;
    }
    
//password 5
//username exist
//password and repassword same
    
}

function focusRegistor(e){
    var theDom = $(e.srcElement);
    theDom.removeClass("error");
}

function infobox(information){
    $(".infobox").html(information)
}

function loginFromHead(){
    var username = $("#username").val();
    var password = $("#password").val();
    //    console.log(username);
    login(username, password);
}
function loginFromForm(){
    var username = $("#formUsername").val();
    var password = $("#formPassword").val();
   
    login(username, password);
}
function changeVerify(){
    var imageDom = $(".verifyCode");
    $(imageDom).attr("src","do?module=verify&random="+Math.random());
}
function login(username , password){
    //check form fields values
    //    $("").validate({
    //        rules:{
    //            
    //        }
    //    });
    //ajax checklogin
    $.ajax({
        async:false,
        method:"get",
        dataType:"json",
        url:"do?module=user",
        data:{
            "action":"login",
            "username":username,
            "password":password
        },
        success:function(returnData){
            if(returnData.status == "success"){
                $(".logined").removeClass("hidden");
                $(".nologin").addClass("hidden");
//                $("#loginform").addClass("hidden");
                $("#loginuser").html(returnData.username);
//                removeFloatbox();
                $("#headerJifen").html("积分("+returnData.points+")");
                user.points=returnData.points;
                user.name=returnData.username;
                cancelForm();
                afterLogin();
            }else{
                alert("登录名或密码有误!")
            }            
        }
    });
}

function afterLogin(){
	
}

function logout(){
    //ajax remove login session   
    location.href = "do?module=user&action=logout";
//    $(".nologin").removeClass("hidden");
//    $(".logined").addClass("hidden");
//    $("#loginuser").html("");
}

function getSchoolLink(catId){
    $.get("do?module=schoollinks&catId="+catId+"&pageId=1",
        function(data){
            $(".SerachResult").html(data);
        });
}

function changeBbreadcrumbs(){
    
}

function pageCategory(pageId){
    var theUrl = changeargs({
        "pageId":pageId,
        "action":"getschoollinks"
    });
    $.get(theUrl, function(returnData){
        $("#searchschool").html(returnData);
        //        console.log(pageId);
        //        console.log(pageCount);
        var searchresultpage = "";      
        var head = "<span><a href='javascript:void(0);' ";
        var tail = "</a></span>";
        if(pageCount <= 3){
            var selected = "";
            for(var index = 1; index <= pageCount;index++){
                selected = " onclick='pageCategory("+index+")'";
                if(index == pageId){
                    selected = "class='selected'";
                }
                searchresultpage += head + selected +">" + index+ tail;
            }
        }else{
            if(pageId > 1){
                var previous = pageId - 1;
                searchresultpage += head + " onclick='pageCategory(1)'><<"+ tail + "...";//go to first
                if(pageId == pageCount && pageId - 1 > 0){
                    var preprevious = previous - 1;
                    searchresultpage += head + " onclick='pageCategory("+preprevious+")'>" + preprevious + tail
                }
                searchresultpage += head + " onclick='pageCategory("+previous+")'>" + previous + tail;
            }
            searchresultpage += head + " class='selected'>" + pageId + tail;//current page
            if(pageId < pageCount){
                var next = pageId + 1;
                var nextHtml = head + " onclick='pageCategory("+next+")'>";
                searchresultpage += nextHtml + next + tail;
                if(pageId == 1 && pageId + 1 < pageCount){
                    var third = next + 1;
                    searchresultpage += head + " onclick='pageCategory("+third+")'>" + third + tail;
                }
                searchresultpage += "..." + head + " onclick='pageCategory("+pageCount+")'>" + ">>" + tail;//last page
            }
        }
      
        $(".searchresultpage").html(searchresultpage);
    });
    
}

/*
 * common functions
 */
//url helper funcition change parameter
//if param exist the replace the value,
//if param not exist then append it;
function changeargs(newargs,url){
    var theurl = url||location.href;
    theurl =  theurl.replace("#","");
    //url   --> http://www.google.com?hello=world&hello2=world2&
    var urls = theurl.split("?");
    var url_args_array = urls[1].split("&");//array("hello=world", "hello2=world2")
    var url_args_json = {};
    for (var args in url_args_array){
        //not include just have & like &hello=world& 's last &
        if(url_args_array[args]){
            var arg = url_args_array[args].split("=");
            //not include &hello=
            if(arg[0]){
                url_args_json[arg[0]] = arg[1];
            }
        }
    }

    //append newargs to url_args
    //here old key-value will be replaced,
    //new key value will be added
    if(newargs != "undefined"){
        for (var tmp in newargs){
            url_args_json[tmp] = newargs[tmp];
        }
    }

    //make urls map to string
    var url_args_string = ""
    for (var tmp in url_args_json){
        url_args_string += tmp + "=" + url_args_json[tmp] + "&";
    }

    if(url_args_string.length > 0){
        return urls[0] +"?" + url_args_string;
    }else{
        return urls[0];
    }
}

/**
 * @param hrefArgs json {"paramName":"paramValue"}
 */
function changeHref(hrefArgs){
    location.href=changeargs(hrefArgs);
}

function CheckEmail(email) {

    AtPos = email.indexOf("@")
    StopPos = email.lastIndexOf(".")

    if (AtPos == -1 || StopPos == -1) {
        return 0;
    } else return 1;

}